package service

import (
	"core/auth"
	"core/coreentity"
	"core/coreservice"
	"core/corestruct"
	"core/myerrors"
	"fmt"
	"ht/api/htuserlogin/data"
)

type mainService struct {
}

// Page Action分页
func (p *mainService) Page(mm *data.HtUserLoginQto, ctx *corestruct.HttpContext) (*corestruct.Page[coreentity.HtUserLogin], error) {
	var db = ctx.DB
	tx := db.Model(&coreentity.HtUserLogin{})
	if mm.Id > 0 {
		tx = tx.Where("id=?", mm.Id)
	} else {
		var dtb, _ = mm.GetDtb()
		if dtb != nil {
			tx = tx.Where("crt_dt>=?", dtb)
		}

		var dte, _ = mm.GetDte()
		if dte != nil {
			tx = tx.Where("crt_dt<?", dte)
		}

		if "" != mm.Key {
			var keyValue = "%" + mm.Key + "%"
			tx = tx.Where("name like ? or  dept_name like ?", keyValue, keyValue, keyValue)
		}

		if "" != mm.State {
			var bIsOnline = 0
			if mm.State == "在线" {
				bIsOnline = 1
			}
			tx = tx.Where("online=?", bIsOnline)
		}
	}
	var svr = &coreservice.PageService[coreentity.HtUserLogin]{}
	r, err := svr.Page(&mm.BasePageQto, ctx, tx)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}

	return r, nil
}

// ForceLx  强制离线
func (p *mainService) ForceLx(mm *corestruct.IdModel, ctx *corestruct.HttpContext) (int64, error) {
	var db = ctx.DB
	var m = &coreentity.HtUserLogin{Id: mm.Id}
	var tx = db.Model(m).
		Select("id,name, online,token").
		Find(m)
	if tx.Error != nil {
		return 0, myerrors.NewByErr(tx.Error)
	}

	if m.Online {
		tx = db.Model(m).Where("id=?", m.Id).
			Update("online", 0)
		if tx.Error != nil {
			return 0, myerrors.NewByErr(tx.Error)
		}
		var logMemo = fmt.Sprintf("强制%s 离线", m.Name)
		ctx.LogMemo = logMemo
	}
	auth.DeleteSession(m.Token)
	return tx.RowsAffected, nil
}

// ForceLx  强制离线
func (p *mainService) SetDebug(mm *data.HtUserLoginDebugDto, ctx *corestruct.HttpContext) (int64, error) {
	var db = ctx.DB
	var m = &coreentity.HtUserLogin{Id: mm.Id}
	var tx = db.Model(m).
		Select("id,name,online,debug").
		Find(m)
	if tx.Error != nil {
		return 0, myerrors.NewByErr(tx.Error)
	}

	if !m.Online {
		return 0, nil
	}
	if m.Debug == mm.Debug {
		return 0, nil
	}
	var bDebug = 0
	if mm.Debug {
		bDebug = 1
	}
	if !m.Debug {
		tx = db.Model(m).Where("id=?", m.Id).
			Update("debug", bDebug)
		if tx.Error != nil {
			return 0, myerrors.NewByErr(tx.Error)
		}
		var logMemo = fmt.Sprintf("设置%s 调试模式：%s", m.Name, mm.Debug)
		ctx.LogMemo = logMemo
	}
	return tx.RowsAffected, nil
}

var (
	MainService = &mainService{}
)
